package main

import (
	"encoding/json"
	"io/ioutil"
	"os"
)

const BackupConfigFileName = "./configs/pushd.json"

type Config struct {
	fileName string

	DBUrl          string
	DBName         string
	DBUser         string //数据库用户名
	DBPwd          string //数据库密码
	CompanyName    string
	CompanyId      int
	TeamName       string
	TeamId         string
	GpsUrl         string
	GpsId          string
	TireUrl        string
	TireId         string
	PushGPS        bool
	PushTireData   bool
	NeedSensorLost bool
	HttpHeaders    []struct {
		Key   string
		Value string
	}
}

func loadConfig(file string) (*Config, error) {
	if file == "" {
		file = os.Args[0] + ".json"
	}
	if _, err := os.Stat(file); os.IsNotExist(err) {
		file = BackupConfigFileName
	}
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	var cfg Config
	err = json.Unmarshal(buf, &cfg)
	if err == nil {
		cfg.fileName = file
	}

	return &cfg, err
}

func (p *Config) Save() error {
	buf, _ := json.MarshalIndent(p, "", "\t")

	return ioutil.WriteFile(p.fileName, buf, os.ModePerm)
}
